<template>
    <div>
        <div v-if="editor">
            <bubble-menu
                class="bubble-menu"
                :tippy-options="{ duration: 100 }"
                :editor="editor"
                >
                <v-btn-toggle
                  dark
                >
                  <v-btn @click="editor.chain().focus().toggleBold().run()" :class="{ 'is-active': editor.isActive('bold') }">
                      <v-icon>mdi-format-bold</v-icon>
                  </v-btn>
                  <v-btn @click="editor.chain().focus().toggleItalic().run()" :class="{ 'is-active': editor.isActive('italic') }">
                    <v-icon>mdi-format-italic</v-icon>
                  </v-btn>
                  <v-btn @click="editor.chain().focus().toggleStrike().run()" :class="{ 'is-active': editor.isActive('strike') }">
                    <v-icon>mdi-format-strikethrough</v-icon>
                  </v-btn>
                </v-btn-toggle>
            </bubble-menu>
        </div>
        <editor-content :editor="editor" />
    </div>
</template>

<script>
import { Editor, EditorContent, BubbleMenu, FloatingMenu } from '@tiptap/vue-2'
import Placeholder from '@tiptap/extension-placeholder'
import StarterKit from '@tiptap/starter-kit'

export default {
  components: {
    BubbleMenu,
    EditorContent,
    FloatingMenu,
  },

  props: {
    value: {
      type: String,
      default: '',
    },
    minHeight: {
      type: Number,
      default: 100,
    },
  },

  data() {
    return {
      editor: null,
    }
  },

  watch: {
    value(value) {
      // HTML
      const isSame = this.editor.getHTML() === value

      // JSON
      // const isSame = JSON.stringify(this.editor.getJSON()) === JSON.stringify(value)

      if (isSame) {
        return
      }

      this.editor.commands.setContent(value, false)
    },
  },

  mounted() {
    this.editor = new Editor({
      content: this.value,
      extensions: [
        StarterKit,
        Placeholder.configure({
          placeholder: '点击输入…',
        }),
      ],
      onUpdate: () => {
        // HTML
        this.$emit('input', this.editor.getHTML())

        // JSON
        // this.$emit('input', this.editor.getJSON())
      },
    })
  },

  beforeDestroy() {
    this.editor.destroy()
  },
}
</script>



<style lang="scss">
/* Basic editor styles */
.ProseMirror {
  min-height: 100px;

  > * + * {
    margin-top: 0.75em;
  }
}

/* Placeholder (at the top) */
.ProseMirror p.is-editor-empty:first-child::before {
  content: attr(data-placeholder);
  float: left;
  color: #adb5bd;
  pointer-events: none;
  height: 0;
}

</style>
